
/* IMPORT */
const electron=window.require("electron")
// import {ipcRenderer as ipc, remote, shell} from 'electron';
const ipc=electron.ipcRenderer;
const remote=electron.remote;
const shell=electron.shell;

const Dialog=window.require('electron-dialog');
// import * as fs from 'fs';
const fs=window.require("fs")
const  mkdirp=window.require('mkdirp');
const os=window.require("os");
import {Store as Container, compose} from 'overstated';
const path=window.require("path");
// import * as pify from 'pify';
const pify=window.require("pify");

import Config from '../../common/config';
import Settings from '../../common/settings';
import Tutorial from '../../containers/main/tutorial';

import File from '../../utils/file';
/* CWD */

class CWD extends Container<CWDState, CWDCTX> {

  /* API */

  get = () => {

    return Config.cwd;

  }

  set = async ( folderPath: string ) => {
    console.log("set");
    console.log(this);

    try {

      const hadTutorial = !!Settings.get ( 'tutorial' );

      await pify ( mkdirp )( folderPath );

      await pify ( fs.access )( folderPath, fs.constants.F_OK );

      Settings.set ( 'cwd', folderPath );

      const notesPath = Config.notes.path,
            hadNotes = ( notesPath && await File.exists ( notesPath ) );

      // if ( !hadTutorial && !hadNotes && Config.flags.TUTORIAL ) {

      //   await this.tutorial.import ();

      //   Settings.set ( 'tutorial', true );

      // }

      ipc.send ( 'cwd-changed' );

    } catch ( e ) {

      Dialog.alert ( `Couldn't access path: "${folderPath}"` );
      Dialog.alert ( e.message );

    }

  }

  select = () => {
    console.log("select===")
    const folderPath = this.dialog ();

    if ( !folderPath ) return;

    return this.set ( folderPath );

  }

  selectDefault = () => {

    const folderPath = path.join ( os.homedir (), '.notable' );

    return this.set ( folderPath );

  }

  openInApp = () => {

    const cwd = this.get ();

    if ( !cwd ) return Dialog.alert ( 'No data directory set' );

    shell.openItem ( cwd );

  }

  dialog = (): string | undefined => {

    const folderPaths = remote.dialog.showOpenDialogSync({
      title: 'Select Data Directory',
      buttonLabel: 'Select',
      properties: ['openDirectory', 'createDirectory', 'showHiddenFiles']
    });

    if ( !folderPaths || !folderPaths.length ) return;

    return folderPaths[0];

  }

}

// /* EXPORT */
// export default ()=>{};
export default compose ({
  tutorial: Tutorial
})( CWD ) as ICWD;
